package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuHasStockVO;
import com.atguigu.common.to.SkuReductionTO;
import com.atguigu.common.to.SpuBoundTO;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Resource
    private SpuInfoDescService spuInfoDescService;
    @Resource
    private SpuImagesService imagesService;
    @Resource
    private AttrService attrService;
    @Resource
    private ProductAttrValueService attrValueService;
    @Resource
    private SkuInfoService skuInfoService;
    @Resource
    private SkuImagesService skuImagesService;
    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    private CouponFeignService couponFeignService;
    @Resource
    private BrandService brandService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private WareFeignService wareFeignService;
    @Resource
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }
    /*查询*/

    /*增*/

    /**
     * 新增商品
     * /product/spuinfo/save
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVO vo) {
        /**
         * 思路:
         * 1.spu各种信息
         *    1.1保存spu基本信息到pms_spu_info表里
         *    1.2商品介绍描述decript都在pms_spu_info_desc表里
         *    1.3spu所有图片都在pms_spu_images表里
         *    1.4保存spu的规格参数,是在SpuSaveVO里面的List<BaseAttrs> baseAttrs;在pms_product_attr_value表里
         *    1.5保存spu的积分信息gulimall_sms->sms_spu_bounds
         *    1.6保存spu对应的sku信息
         * 2.sku的各种信息
         *    2.1保存sku基本信息到pms_sku_info
         *    2.2保存sku的图片信息到pms_sku_images
         *    2.3保存sku的销售属性信息到pms_sku_sale_attr_value
         *    2.4保存sku的优惠,满减等信息  跨库了gulimall_sms->sms_sku_ladder sms_sku_full_redu
         */
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);

        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        descEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        List<String> images = vo.getImages();
        imagesService.saveImages(infoEntity.getId(), images);

        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity id = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(id.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(infoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);

        Bounds bounds = vo.getBounds();
        SpuBoundTO spuBoundTO = new SpuBoundTO();
        BeanUtils.copyProperties(bounds, spuBoundTO);
        spuBoundTO.setSpuId(infoEntity.getId());
        R r1 = couponFeignService.saveSpuBounds(spuBoundTO);
        if (r1.getCode() != 0) {
            log.error("远程保存sku优惠信息失败");
        }


        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    // 返回true就是需要,false就是过滤掉
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);
                // TODO 没有图片路径的无需保存

                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                SkuReductionTO skuReductionTO = new SkuReductionTO();
                BeanUtils.copyProperties(item, skuReductionTO);
                skuReductionTO.setSkuId(skuId);
                if (skuReductionTO.getFullCount() > 0 || skuReductionTO.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r = couponFeignService.saveSkuReduction(skuReductionTO);
                    if (r.getCode() != 0) {
                        log.error("远程保存spu积分信息失败");
                    }
                }

            });
        }

    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.baseMapper.insert(infoEntity);
    }

    /**
     * /product/spuinfo/list    spu检索
     * 根据开发文档传来的参数有:key  catelogId  brandId  status
     * 响应的数据有:
     * 分页参数  "list": [{
     * <p>
     * "brandId": 0, //品牌id
     * "brandName": "品牌名字",
     * "catalogId": 0, //分类id
     * "catalogName": "分类名字",
     * "createTime": "2019-11-13T16:07:32.877Z", //创建时间
     * "id": 0, //商品id
     * "publishStatus": 0, //发布状态
     * "spuDescription": "string", //商品描述
     * "spuName": "string", //商品名字
     * "updateTime": "2019-11-13T16:07:32.877Z", //更新时间
     * "weight": 0 //重量
     * }]
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");// map.get("key");通过key获取val,先判断val(检索条件)是否为空
        if (!StringUtils.isEmpty(key)) {// 如果val不为空,说明前端传来了检索条件
            wrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        // status = 1 and (id=1 or spu_name like xxx) 现在知道为啥要用括号括起来吧?不用括号你只要spu_name = xxx前面的条件就可以不用管了
        String status = (String) params.get("status");// map.get("key");通过key获取val,先判断val(检索条件)是否为空
        if (!StringUtils.isEmpty(status)) {// 如果val不为空,说明前端传来了检索条件
            wrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");// map.get("key");通过key获取val,先判断val(检索条件)是否为空
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)) {// 如果val不为空,说明前端传来了检索条件
            wrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");// map.get("key");通过key获取val,先判断val(检索条件)是否为空
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)) {// 如果val不为空,说明前端传来了检索条件
            wrapper.eq("catalog_id", catelogId);
        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /*删*/

    /*改*/

    /**
     * 商品上架功能   POST:/product/spuinfo/{spuId}/up
     * 请求的参数:spuId
     * 响应的数据
     * {
     * "msg": "success",
     * "code": 0
     * }
     */
    @Override
    public void up(Long spuId) {
        // 1.查出当前spuId对应的所有sku信息   品牌的名字
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkuBySpuId(spuId);
        List<Long> skuIdList = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());


        // TODO  查询当前sku的所有可以被检索的规格属性
        /**
         * attrs中的attrId,attrName,attrValue
         * 这些规格属性有一个特点,商品有很多规格,但是pms_attr表里有些可以被检索,我们要查出来,有些不能被检索(基本信息)就不用查出来
         * 如果在循环内部差,我们有8个sku,就要查8遍,但是这些信息都一样了,所以把他拿到了外面来查,就查一次
         */
        List<ProductAttrValueEntity> baseAttrs = attrValueService.baseAttrListForSpu(spuId);// 我们之前写过的spuId对应的所有attr信息,这个是中间实体类,从中取出attr信息就可以了
        List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> searchAttrId = attrService.selectSearchAttrs(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrId);// list集合转set集合还能这么搞?构造方法?进源码看看去吧
        // 还记得SkuEsModel里面的内部类Attrs吗
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());


        // TODO 发送远程调用,库存系统查询是否有库存
        Map<Long,Boolean> stockMap = null;
        try{
            R r = wareFeignService.getSkuHasStock(skuIdList);
            TypeReference<List<SkuHasStockVO>> typeReference = new TypeReference<List<SkuHasStockVO>>() {
            };
            stockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVO::getSkuId,item->item.getHasStock()));
        }catch (Exception e){
            log.error("库存服务查询异常:原因{}",e);
        }



        // 2.封装每个sku信息
        Map<Long,Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skuInfoEntities.stream().map(sku -> {
            // 组装需要的数据
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            /**
             * 对比sku和skuEsModel,看除了对拷的属性外,哪些属性skuInfoEntity没有需要单独处理
             * skuPrice,skuImg,hasStock,hotScore,brandName,brandImg,catalogName,attrs中的attrId,attrName,attrValue
             * 以上属性SkuEsModel都需要,但是skuInfoEntity没有,因此需要单独处理
             */
            // skuPrice,skuImg
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            // hasStock,hotScore
            /**
             * 设置库存信息
             */
            if (finalStockMap == null){
                skuEsModel.setHasStock(true);
            }else{
                skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }
            // TODO 热度评分
            skuEsModel.setHotScore(0L);// 为了简单先默认给个0


            // brandName brandImg  catalogName
            BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            // attrs中的attrId,attrName,attrValue只需要查一次,所以我放到外面了
            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());

        // TODO 发给es进行保存:gulimall-search
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode() == 0){
            // 添加成功,因为成功的状态码是0
            // TODO pms_spu_info里面的publish_status发布状态改为1,已上架
            baseMapper.updateSpuStatus(spuId,ProductConstant.ProductStatusEnum.SPU_UP.getCode());
        }else {
            // 远程调用失败
            // TODO 重复调用?接口幂等性?重试机制?
        }
    }
}